package com.etlmaster.executor.utils;

import java.io.IOException;
import java.util.Map;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.etlmaster.executor.annotation.StepInstruction;

public class ScanPackage {
	public static void autoScanStepInstruction(String basepkg,boolean isPlugin,Map<String, String> STEP_INST_CLASS_MAPP) {
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		String packageSearchPath = "classpath*:" + basepkg + "/**/*.class";
		try {
			Resource[] resources = resourcePatternResolver
					.getResources(packageSearchPath);
			for (Resource resource : resources) {
				String uri = resource.getURI().toString();
				String className = uri.substring(uri.indexOf(basepkg),
						uri.length() - 6).replace('/', '.');
				Class cls = Class.forName(className);
				if (cls.isAnnotationPresent(StepInstruction.class)) {
					String key = ((StepInstruction) cls
							.getAnnotation(StepInstruction.class)).value()[0];

					if (STEP_INST_CLASS_MAPP.containsKey(key)) {
						LogWriter.addLog("WARN", "出现重复的指令类{}与{}",
								STEP_INST_CLASS_MAPP.get(key), className+"Meta");
						if(isPlugin){
							STEP_INST_CLASS_MAPP.remove(key);// 删除已经存在的方法
							STEP_INST_CLASS_MAPP.put(key, className + "Meta");
						}

					} else {
						STEP_INST_CLASS_MAPP.put(key, className + "Meta");
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}


}
